package com.wswy.wzcx.ui.module.oilprice

import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.text.format.DateFormat
import com.blankj.utilcode.util.SPUtils
import com.che.libcommon.utils.JsonKit
import com.che.libcommon.utils.RxBus
import com.wswy.wzcx.api.Api
import com.wswy.wzcx.model.WZCity
import com.wswy.wzcx.model.resp.OilPriceResp
import com.wswy.wzcx.module.InternalMsgCode
import com.wswy.wzcx.module.LocManager
import com.wswy.wzcx.module.base.BaseViewModel
import com.wswy.wzcx.module.base.Resource
import com.wswy.wzcx.module.base.onResult
import io.reactivex.observers.ResourceObserver
import java.util.*

class OilViewModel : BaseViewModel() {


    private val oilPriceLiveData = MutableLiveData<Resource<OilPriceResp?>>()
    var localCity : WZCity?=null
    private set

    override fun onCreate() {
        super.onCreate()
        kotlin.runCatching {

            localCity = LocManager.getInstance().currentWZCity

        }

        localCity?:kotlin.run {
            localCity = WZCity.DEFAULT
        }

    }

    fun onChangeCity(city:WZCity){

        localCity = city

        LocManager.getInstance().saveWZCity(city)
    }

    fun load(pid:Int?=localCity?.pid){

        oilPriceLiveData.postValue(Resource.loading())

        addRun(Api.get().oilPriceList(pid?:3).onResult({

            oilPriceLiveData.postValue(Resource.success(it))

        },{

        }))
    }


    fun getPriceVos():Map<String,ArrayList<OilPriceVo>>?{

        val list92 = ArrayList<OilPriceVo>()
        val list95 = ArrayList<OilPriceVo>()
        val listd0 = ArrayList<OilPriceVo>()

        var has92 = true
        var has95 = true
        var hasd0 = true

        oilPriceLiveData.value?.data?.list?.sortedBy { it.createdDate }?.forEachIndexed { index, oilPriceModel ->

            val date = DateFormat.format("MM-dd",(oilPriceModel.createdDate?:0) * 1000).toString()

            if (has92 && oilPriceModel.g92?:0f == 0f){
                has92 = false
            }

            if (has95 && oilPriceModel.g95?:0f == 0f){
                has95 = false
            }

            if (hasd0 && oilPriceModel.d0?:0f == 0f){
                hasd0 = false
            }

            list92.add(OilPriceVo(index,oilPriceModel.g92?:0f,date))
            list95.add(OilPriceVo(index,oilPriceModel.g95?:0f,date))
            listd0.add(OilPriceVo(index,oilPriceModel.d0?:0f,date))

        }

        val map = hashMapOf<String,ArrayList<OilPriceVo>>()

        if (has92){
            map.put("92#",list92)
        }
        if (has95){
            map.put("95#",list95)
        }
        if (hasd0){
            map.put("d0#",listd0)
        }
        return map
    }

    fun getOilPriceLiveData():LiveData<Resource<OilPriceResp?>> = oilPriceLiveData

}